package io.chenhd.gateway.config;

import io.chenhd.gateway.router.HttpEndpointRouter;
import io.chenhd.gateway.router.RandomHttpEndpointRouter;
import io.chenhd.gateway.router.RoundHttpEndpointRouter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by chenhd on 2021/8/22.
 */
public class RouterConfig {
    public static HashMap<String, HttpEndpointRouter> routerMap = new HashMap<>();
    public static HashMap<String, String> ipList = new HashMap<>();

    static {
        routerMap.put("/router1", new RandomHttpEndpointRouter());
        routerMap.put("/router2", RoundHttpEndpointRouter.getInstance());

        ipList.put("/router1", "http://localhost:8801,http://localhost:8802");
        ipList.put("/router2", "http://localhost:8801,http://localhost:8802");
    }

    public static String getBackendUrl(String uri) {
        for (Map.Entry<String, HttpEndpointRouter> routerEntry : RouterConfig.routerMap.entrySet()) {
            if (uri.contains(routerEntry.getKey())) {
                HttpEndpointRouter router = routerEntry.getValue();
                List<String> backendUrls = Arrays.asList(RouterConfig.ipList.get(routerEntry.getKey()).split(","));
                return router.route(backendUrls);
            }
        }
        return null;
    }
}
